/*
 * Copyright 2018 the original author or authors.
 * 
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 * 
 * 
 * 
 * 
 */
package org.liang.downimage.core;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.liang.downimage.config.AppConfig;
import org.liang.downimage.util.CheckUtil;

/**
 * 下载图片类，根据搜索地址，获取网络图片地址
 * @author houliang
 * @date 2018年1月27日
 */
public class SearchImage {
	/**保存未访问过的图片地址*/
	private static List<String> visitedUrls = new ArrayList<String>();
	/**保存已经访问过的图片地址*/
	private static Queue<String> unVisitedUrls = new LinkedList<String>();
	
	/**
	 * 根据搜索地址，获取网络图片地址
	 * @param url 网络地址
	 */
	public static void downImage(String url) {
		if (url==null || !CheckUtil.checkDir()) {
			return;
		}
		
		try {
			Document doc = Jsoup.connect(url).get();
			Elements elements = doc.getElementsByTag("img");
			for (Element element : elements) {
				String imgSrc = element.attr("abs:src");

				int index = imgSrc.lastIndexOf(".");
				if (index == -1) {
					continue;
				}
				String imageType = imgSrc.substring(index+1);
				if (!CheckUtil.containImgageType(imageType)) {
					continue;
				}
				if(visitedUrls.contains(imageType)) {
					continue;
				}
				visitedUrls.add(imgSrc);
				unVisitedUrls.offer(imgSrc);
			}

			DownImageThread downImage = new DownImageThread();
			downImage.initUrl(unVisitedUrls);
			unVisitedUrls.clear();
			for (int i = 0; i < AppConfig.threadNum; i++) {
				new Thread(downImage).start();
			}

			// 创建一个线程池
//			ExecutorService executorService = Executors.newFixedThreadPool(AppConfig.threadNum);
//			for (int i = 0; i < AppConfig.threadNum; i++) {
//				executorService.submit(downImage);
//			}
//			executorService.shutdown();
		} catch (Exception e) {
			System.out.println("错误地址：" + url);
			e.printStackTrace();
		}
	} 
}
